import bus from '@/store/bus.js'
import { v4 as uuidv4 } from "uuid";
import CryptoJS from 'crypto-js';
import axios from "axios";
import serialize from './obj2str'
import xe from 'xe-utils'
import dayjs from "dayjs";
import weekday from 'dayjs/plugin/weekday'
import 'dayjs/locale/zh-cn'
import xeditor from "@/lui/editor";
import { useRequestOldRoutes } from "@/store/requestOldRoutes";
import { TinyModal, TinyNotify } from '@opentiny/vue'
import Cookies from "js-cookie";
import {useGlobal} from "@/store/globalStore";
let urlTestV4 = 'http://localhost:996/'
let urlProV4 = 'https://v5api.sanzhiyun.cn/'
let webUrl = process.env.NODE_ENV ==='development' ? 'http://localhost:996/' : 'https://v5.sanzhiyun.cn/'
let baseUrlV4 = process.env.NODE_ENV ==='development' ? urlTestV4 : urlProV4

dayjs.extend(weekday)
dayjs.locale('zh-cn')
let tool = {
    baseUrl: urlProV4,
    xe: xe,
    dayjs: dayjs,
    webUrl,
}

tool.data = {
    set(key, data) {
        localStorage.setItem(key, JSON.stringify(data))
    },
    get(key) {
        try {
            return JSON.parse(localStorage.getItem(key))
        } catch (err) {
            return null
        }
    },
    remove(key) {
        return localStorage.removeItem(key)
    },
    clear() {
        return localStorage.clear()
    },
    getTenantId () {
        let usr = tool.data.getUser()
        if(usr) {
            return usr.tenantId
        }
        return null
    },
    getUser () {
        let usr = tool.data.get("v5UserInfo")
        if(usr) {
            return usr
        }
        return null;
    },
    getUserId () {
        let usr = tool.data.getUser()
        return usr ? usr.id : null;
    },
    getUserName () {
        let usr = tool.data.getUser()
        return usr ? usr.name : null;
    },
    logout() {
        localStorage.clear()
        tool.Session.clear()
    },
    setUser (data) {
        tool.data.set('v5UserInfo', data)
        tool.data.set('token', data.token)
    },
}
tool.Session = {
    // 设置临时缓存
    set(key, val) {
        if (key === 'token') return Cookies.set(key, val);
        window.sessionStorage.setItem(key, JSON.stringify(val));
    },
    // 获取临时缓存
    get(key) {
        if (key === 'token') return Cookies.get(key);
        let json = window.sessionStorage.getItem(key);
        return JSON.parse(json);
    },
    // 移除临时缓存
    remove(key) {
        if (key === 'token') return Cookies.remove(key);
        window.sessionStorage.removeItem(tool.data.setKey(key));
    },
    // 移除全部临时缓存
    clear() {
        Cookies.remove('token');
        window.sessionStorage.clear();
    },
}

tool.editor = (options) => {
    const global = useGlobal()
    if(!global.editorOpened) {
        xeditor(options)
        global.editorOpened = true
    }
}
tool.add = (...vars) => {
    let len = vars.length
    let sum = 0
    for (let i = 0; i < len; i++) {
        sum = xe.add(sum,vars[i])
    }
    return sum
}
tool.minus = (...vars) => {
    let len = vars.length
    let sum = vars[0]
    for (let i = 1; i < len; i++) {
        sum = xe.subtract(sum,vars[i])
    }
    return sum
}
tool.divide = (...vars) => {
    let len = vars.length
    let sum = vars[0]
    for (let i = 1; i < len; i++) {
        sum = xe.divide(sum,vars[i])
    }
    return sum
}
tool.multiply = (...vars) => {
    let len = vars.length
    let sum = vars[0]
    for (let i = 1; i < len; i++) {
        sum = xe.multiply(sum,vars[i])
    }
    return sum
}
// 组合列表显示 的字段
tool.info = (msg) => {
    TinyNotify({
        type: 'info',
        title: '提示',
        message: msg,
        position: 'top-right',
        duration: 2000,
        customClass: 'my-custom-cls'
    })
}
tool.suc = (msg) => {
    TinyNotify({
        type: 'success',
        title: '提示',
        message: msg,
        position: 'top-right',
        duration: 2000,
        customClass: 'my-custom-cls'
    })
}
tool.err = (msg) =>{
    TinyNotify({
        type: 'error',
        title: '提示',
        message: msg,
        position: 'top-right',
        duration: 2000,
        customClass: 'my-custom-cls'
    })
}
tool.warning = (msg) =>{
    TinyNotify({
        type: 'warning',
        title: '提示',
        message: msg,
        position: 'top-right',
        duration: 2000,
        customClass: 'my-custom-cls'
    })
}
tool.confirm = (msg, title = '操作提示', load) => {
    return new Promise((resolve) => {
        TinyModal.confirm(msg, title).then((res) => {
            if(res === 'confirm') {
                resolve()
            }
            else {
                if(typeof load !== 'undefined') {
                    load.loading = false
                }
            }
        })
    })
}
// 关闭loading层
tool.hide = (timeout = 10) => {
    setTimeout(() => {
        bus.$emit('doLoading', false)
    }, timeout)
}
// 显示 页面加载
tool.loading = () => {
    bus.$emit('doLoading', true)
}
tool.uuid = () => {
    return uuidv4();
}
tool.crypto = {
    //MD5加密
    MD5(data){
        return CryptoJS.MD5(data).toString()
    },
}
tool.encodeStr = (str) => {
    let secretKey = "jsonaes"
    return  CryptoJS.AES.encrypt(str, secretKey).toString();
}
tool.decodeStr = (str) => {
    let secretKey = "jsonaes"
    return  CryptoJS.AES.decrypt(str, secretKey).toString(CryptoJS.enc.Utf8);

}
tool.trim = (str) => {
    return str.replace(/\s+/g, "")
}
tool.post =  (url, data = {}, load, ctype = 'application/json') => {
    data.ter = 'pc'
    let userInfo = tool.data.getUser()
    let token = userInfo ? userInfo.token : ''
    postLoading(load, true)
    let uname = tool.data.get('usernameAss')
    if (uname) {
        data.usernameAss = uname
    }
    return axios.post(url, data, {
        baseURL: baseUrlV4,
        headers: {
            token: token ? token : '', 'Content-Type': ctype
        }
    })
        .then(ret => {
            if (ret && ret.data) {
                let data = ret.data
                if(data.msg === '登录过期,请重新登录') {
                    tool.data.logout()
                }
                if (data.stat && data.msg)  {
                    tool.suc(data.msg)
                }
                if (!data.stat && data.msg)  {
                    tool.warning(data.msg)
                }
                return Promise.resolve(data)
            } else {
                tool.err('读取失败')
                return Promise.resolve(false)
            }

        })
        .catch(errs => {
            let r = errs.response
            if (r && r.status && r.status === 401) {
                if (r.data && r.data.msg) {
                    tool.err(r.data.msg)
                }
            }
            return Promise.resolve(false)
        })
        .finally(() => {
            setTimeout(() => {
                postLoading(load, false)
            }, 300)
        })
}
const postLoading = (load, val) => {
    if(typeof load === 'boolean' && load === true) {
        bus.$emit('doLoading', val)
    }
    else if(typeof load === 'object') {
        load.loading = val
    }
}
// 时间加减方法
// 时间加减方法
tool.getDay = (day= '', diff = 0, addType = 'day', format = 'YYYY-MM-DD') => {
    return dayjs(day?day:dayjs()).add(diff, addType).format(format)
}
tool.dateFormat = (day, format = 'YYYY-MM-DD') => {
    return  dayjs(day?day:dayjs()).format(format)
}
tool.datetime = (day, format = 'YYYY-MM-DD HH:mm:ss') => {
    return  dayjs(day?day:dayjs()).format(format)
}
// type = beg|end 开始日期|结束日期,diff 加减数量,unit MONTH|DAY|YEAR  current 当前时间
tool.getDayStart = (current = '', type = 'beg', diff = 0, unit = 'MONTH') => {
    if (type === 'beg'){
        return   dayjs(current ? current : dayjs()).add(diff, unit).startOf(unit).format('YYYY-MM-DD')
    }
    if (type === 'end'){
        return   dayjs(current ? current : dayjs()).add(diff, unit).endOf(unit).format('YYYY-MM-DD')
    }
}
//
tool.getBillState = () => {
    return [
        {id:'draft', name: '草稿'},
        {id:'accounted', name: '已审核'},
        {id:'del', name: '已删除'},
        {id:'all', name: '全部'},
    ]
}
tool.toPrint = (printList, direct = false, isCard = false) => {
    if (printList.length === 0) return tool.err('至少选择 1 行记录进行操作')
    let ids = []
    for (let i = 0; i < printList.length; i++) {
        ids.push(printList[i].id)
    }
    if(ids.length > 20) return tool.err('不能批量打印超过 20 条数据')
    // eslint-disable-next-line no-undef
    const LODOP = (typeof getCLodop==='function') ? getCLodop() : ''
    if (!LODOP) {
        tool.post('common/getPrintUrl', {}).then(ret => {
            if(ret.stat) {
                window.location.href = ret.data
            }
        })
        return tool.info('正在下载打印控件,下载完成后请解压并安装。')
    }
    LODOP.SET_PRINT_MODE('CATCH_PRINT_STATUS', true)
    LODOP.SET_LICENSES("","C748D766DD08B5AE84E6BC2F3A546E6C7C9","","");
    tool.post('print/getPrint', {ids: ids , isCard: isCard,direct: false}, true).then(ret => {
        if (ret.stat) {
            let data = ret.data
            let evals = data.evals
            let taskId = data.task_id
            for (let i = 0; i < evals.length; i++) {

                if (evals[i].str) {
                    new Function('LODOP',' return ' + evals[i].str)(LODOP)
                }
                else {
                    LODOP.ADD_PRINT_TABLE(0,15,'96%','100%', evals[i].data)
                }
            }
            if (LODOP.CVERSION){
                LODOP.On_Return = (TaskID, Value)=> {
                    if(Value === true || tool.xe.toNumber(Value) === 1) {
                        bus.$emit('printSuc')
                        tool.suc('已打印')
                        tool.post('print/printSuc', {taskId: taskId}, false).then((ret) => {})
                    }
                        // tool.post('print/printSuc', {taskId: taskId}, false).then(() => {})
                    // let strResult = LODOP.GET_VALUE('PRINT_STATUS_EXIST')
                }

                if (direct) {
                    LODOP.PRINT()

                }
                else {
                    LODOP.PREVIEW()
                }

            }
        }
    })
}

tool.toArrayTree = (ret) => {
    ret.map(row => {
        row.pid = row.pid ? row.pid : null
    })
    return xe.toArrayTree(ret, { parentKey: "pid", strict: true });
}
tool.toTreeArray = (ret) => {
    return xe.toTreeArray(ret, { clear: true });
}
// 组合查询条件
tool.setSearch = (formData, searchRule) => {
    let where = []
    for (let i in formData) {
        if (i && formData[i]) {
            searchRule.map(s => {
                if (s.field === i) {
                    let sop = s.sop ? s.sop : '='
                    if (sop === 'include') {
                        where.push(` ${i} like '%${formData[i]}%' `)
                    }
                    else {
                        if(s.dataType) {
                            if(s.dataType === 'string') {
                                if(s.realField) {
                                    where.push(` ${s.realField} ${s.sop} '${formData[i]}' `)
                                }
                                else {
                                    where.push(` ${i} ${s.sop} '${formData[i]}' `)
                                }
                            }
                        }
                        else {
                            where.push(` ${i} ${s.sop} ${formData[i]} `)
                        }
                    }
                }
            })
        }
    }
    return where
}
// 获取地址 经纬度
tool.getLngLat = (callback) => {
    AMapLoader.load({
        key:"3c8e3c44ae26cd3674ad328c481fc6e3",             // 申请好的Web端开发者Key，首次调用 load 时必填
        version:"2.0",      // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins:['AMap.Geolocation', 'AMap.Geocoder'],       // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    }).then((AMap) => {
        let geolocation = new AMap.Geolocation({
            enableHighAccuracy: true, // 是否使用高精度定位，默认：true
            timeout: 10000, // 设置定位超时时间，默认：无穷大
            offset: [10, 20],  // 定位按钮的停靠位置的偏移量
            zoomToAccuracy: true,  //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            position: 'RB' //  定位按钮的排放位置,  RB表示右下
        })
        geolocation.getCurrentPosition(function(status,result){
            if(status === 'complete') {
                onComplete(result)
            }
            else {
                onError(result)
            }
        })
        const onComplete = (data) => {
            // data是具体的定位信息
            let lnglat = [data.position.lng, data.position.lat ]
            let geocoder = new AMap.Geocoder({
                city: '028' // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
            })
            geocoder.getAddress(lnglat, (status, result) => {
                if (status === 'complete' && result.info === 'OK') {
                    // result为对应的地理位置详细信息
                    let obj = {
                        lnglat: lnglat,
                        address: result.regeocode.formattedAddress
                    }
                    callback(obj)
                } else {
                    tool.err('定位失败')
                    callback(false)
                }
            })
        }
        const onError = () => {
            // 定位出错
            tool.err('定位失败')
            callback(false)
        }
    }).catch(() =>{
        callback(false)
    })
}

tool.obj2str = serialize
tool.str2obj = (str) => {
    return new Function('return ' + str)()
}

tool.billToRoute = (billNo) => {
    if(billNo.indexOf('SK') === 0) {
        return 'receipt'
    }
    if(billNo.indexOf('XS') === 0) {
        return 's-in'
    }
    if(billNo.indexOf('XT') === 0) {
        return 's-out'
    }
    if(billNo.indexOf('XH') === 0) {
        return 's-t'
    }
    if (billNo.indexOf('FK') === 0) {
      return 'payment'
    }
    if(billNo.indexOf('CG') === 0) {
        return 'pur-in'
    }
    if(billNo.indexOf('CT') === 0) {
        return 'pur-out'
    }
    return false
}

tool.toAssQty = (row) => {
    let m = Math.floor(row.qty/row.spec)
    let m2 = row.qty%row.spec
    let ass = ''
    if(m > 0) ass += m+row.unit1
    if(m2 > 0) ass += ' ' + m2+row.unit2
    return ass
}
tool.getRoute = (routeName) => {
    let {requestOldRoutes} = useRequestOldRoutes()

    let route = requestOldRoutes.filter(row => {
        return row.name === routeName
    })
    if(route.length === 1) {
        return route[0]
    }
    return null
}
tool.getMenuList = async () => {
   let ret = await tool.post('menu/getMenuList1', {})
    let data = ret.data
    let menu = {
        id: -1,
        pid: 0,
        sort: 12,
        icon: 'star-off',
        name: '常用',
        display: 1
    }
    if (data && data.length > 0) {
        data.splice(0,0,menu)
        // let menuList = tool.data.get('jsonMenu')
    }
    return data
}

tool.getOptions = async () => {
   let options = await tool.post('sets/getParams').then(ret => {
        return JSON.parse(ret.data.value)
    })
    return options
}

tool.updateVer = () => {
    let localVer = tool.data.get('ver') //
    tool.post('app/getPcVer').then(ret => {
        if(ret.stat) {
            let onlineVer = (ret.data && ret.data.ver)?ret.data.ver:null
            if(localVer) {
                if(onlineVer) {
                    if(localVer !== onlineVer) {
                        // 本地版本与线上版本不一样，更新
                        updateVer(ret)
                    }
                }
            }
            else {
                if(onlineVer) {
                    // 没有本地版本
                    updateVer(ret)
                }
            }
        }
    })
}

tool.getPageRule = async (whichPage) => {
    const ret = await tool.post('page/getPageRule', { whichPage: whichPage }, true)
    if (ret.stat && ret.data) {
        return JSON.parse(ret.data)
    }
    return null
}

tool.getHelp = (routeName) => {
    tool.post('sets/getHelpById', {routeName}).then(ret => {
        if(ret.stat && ret.data) {
            // helpContent.value = ret.data
        }
    })
}

tool.sendToPy = (obj) => {
    if(typeof qt !== 'undefined') {
        new QWebChannel(qt.webChannelTransport, (channel) => {
            // 获取 Python 中注册的对象
            window.bridge = channel.objects.bridge;
            window.bridge.send_message(JSON.stringify(obj), (response) => {

            })
        })
    }
}
const updateVer = (ret) => {
    let msg = ret.data.msg
    let onlineVer = (ret.data && ret.data.ver)?ret.data.ver:null
    tool.confirm(msg, '更新提示' + (ret.data.needLogin?'(需重新登录)':'')).then(() => {
        tool.data.set('ver', onlineVer)
        tool.suc('更新中....')
        if(ret.data.needLogin) {
            tool.data.logout()
        }
        window.location.reload()
    })
}

export default tool
